package com.admin_system.utils;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@Component
public class MergeWordUtil {
    /**
     * 合并多个 Word 文档，并将结果写入 OutputStream
     *
     * @param files       需要合并的 Word 文件列表
     * @param outputStream 合并后的文档输出流
     * @throws Exception 合并过程中可能抛出的异常
     */
    public  void mergeMroeWord(List<File> files, OutputStream outputStream) throws Exception {
        ArrayList<XWPFDocument> documentList = new ArrayList<>();
        XWPFDocument doc = null;
        // 读取所有文件
        for (File file : files) {
            try (FileInputStream in = new FileInputStream(file)) {
                OPCPackage open = OPCPackage.open(in);
                XWPFDocument document = new XWPFDocument(open);
                documentList.add(document);
            }
        }
        // 合并文档
        for (int i = 0; i < documentList.size(); i++) {
            doc = documentList.get(0);
            if (i == 0) {
                documentList.get(i).createParagraph().createRun().addBreak(BreakType.PAGE);
            } else if (i == documentList.size() - 1) {
                appendBody(doc, documentList.get(i));
            } else {
                documentList.get(i).createParagraph().createRun().addBreak(BreakType.PAGE);
                appendBody(doc, documentList.get(i));
            }
        }
        // 将合并后的文档写入输出流
        if (doc != null) {
            doc.write(outputStream);
        }
    }
    /**
     * 将一个文档的内容追加到另一个文档中
     *
     * @param destDoc 目标文档
     * @param srcDoc  源文档
     */
    private  void appendBody(XWPFDocument destDoc, XWPFDocument srcDoc) {
        for (int i = 0; i < srcDoc.getParagraphs().size(); i++) {
            destDoc.createParagraph().getCTP().set(srcDoc.getParagraphs().get(i).getCTP());
        }
        for (int i = 0; i < srcDoc.getTables().size(); i++) {
            destDoc.createTable().getCTTbl().set(srcDoc.getTables().get(i).getCTTbl());
        }
    }
}
